package pl.lsierant.j2me.bipacz.store;

import java.io.DataOutputStream;
import java.util.Hashtable;

import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;

public class Records {
    private String recordStoreName;
    private Hashtable settings;

    public Records(String recordStoreName) throws RecordStoreException {
        this.recordStoreName = recordStoreName;
        settings = new Hashtable();
        load();
    }

    public Object get(String key) {
        return settings.get(key);
    }

    public void put(String key, Object value) {
        if (key != null && value != null) {
            settings.put(key, value);
        }
    }

    public void load() throws RecordStoreException {
        DataOutputStream out = new DataOutputStream(null);

        RecordStore rs = null;
        RecordEnumeration re = null;

        try {
            rs = RecordStore.openRecordStore(recordStoreName, true);
            re = rs.enumerateRecords(null, null, false);

            while (re.hasNextElement()) {

            }
        } finally {
            if (re != null) {
                re.destroy();
            }
            if (rs != null) {
                rs.closeRecordStore();
            }
        }
    }

    public void save() throws RecordStoreException {
        RecordStore rs = null;
        RecordEnumeration re = null;

        try {
            rs = RecordStore.openRecordStore(recordStoreName, true);
            re = rs.enumerateRecords(null, null, false);

            while (re.hasNextElement()) {
                int id = re.nextRecordId();
                rs.deleteRecord(id);
            }

            // TODO: add records
        } finally {
            if (re != null) {
                re.destroy();
            }
            if (rs != null) {
                rs.closeRecordStore();
            }
        }
    }

    public void delete() throws RecordStoreException {
        RecordStore.deleteRecordStore(recordStoreName);
    }

    public void deleteRecords() throws RecordStoreException {
        RecordStore rs = null;
        RecordEnumeration re = null;

        try {
            rs = RecordStore.openRecordStore(recordStoreName, true);
            re = rs.enumerateRecords(null, null, false);

            while (re.hasNextElement()) {
                int id = re.nextRecordId();
                rs.deleteRecord(id);
            }
        } finally {
            if (re != null) {
                re.destroy();
            }
            if (rs != null) {
                rs.closeRecordStore();
            }
        }
    }
}
